//
//  WPCoinRecordVC.m
//  wobingwoyi
//
//  Created by WGP on 16/8/5.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPCoinRecordVC.h"
#import "WPGoldRecordsModel.h"
#import "WPGoldRecordCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "WPMineLoginVC.h"

@interface WPCoinRecordVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (weak, nonatomic) IBOutlet UIImageView *topLineView;
@property(nonatomic, strong)NSMutableArray *models;
@property(nonatomic,assign)int indexPage;

@end

static NSString *ID = @"cell";
@implementation WPCoinRecordVC

-(NSMutableArray *)models
{
    if (_models == nil)
    {
        _models = [NSMutableArray array];
    }
    return _models;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    self.myTableView.backgroundColor = GlobalBgColor;
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    tableHeaderView.backgroundColor = GlobalBgColor;
    self.myTableView.tableHeaderView = tableHeaderView;
    self.myTableView.tableFooterView = [UIView new];
    [self.myTableView registerClass:[WPGoldRecordCell class] forCellReuseIdentifier:@"WPGoldRecordCell"];
    
    
    /* 配置下拉刷新控件 */
    MJRefreshNormalHeader *mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //      刷新数据
        [self loadGoldRecords];
        
    }];
    self.myTableView.mj_header = mj_header;
    [mj_header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [mj_header setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [mj_header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    mj_header.stateLabel.textColor = GLobalFontColor;
    mj_header.lastUpdatedTimeLabel.textColor = GLobalFontColor;
    
    //    上拉刷新控件
    MJRefreshAutoFooter *mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self loadMoreData];
        [self.myTableView.mj_footer endRefreshing];
        
    }];
    self.myTableView.mj_footer = mj_footer;
    mj_footer.automaticallyRefresh = NO;
    mj_footer.automaticallyHidden = NO;
    
    [self loadGoldRecords];
}

-(void)loadGoldRecords
{
    [self showWithStatus:@"正在加载"];
    NSString *url = @"user/getExchRecord.do";
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            [self.models removeAllObjects];
            
            if([responseObject[@"detail"] count])
            {
                for (NSDictionary *recordDict in responseObject[@"detail"])
                {
                    WPGoldRecordsModel *model = [WPGoldRecordsModel yy_modelWithDictionary:recordDict];
                    [self.models addObject:model];
                }
                
                if ([responseObject[@"detail"] count] < 10)
                {
                    self.myTableView.mj_footer.hidden = YES;
                }
                else
                {
                    [self.myTableView.mj_footer endRefreshing];
                }
                
                self.indexPage = 1;
                [self.myTableView reloadData];
            }
            else
            {
                self.myTableView.hidden = YES;
                self.topLineView.hidden = YES;
            }
            
            [self dismiss];
        }
        else
        {
//            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //                账号过期
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            else
            {
                [self showErrorInfoWithStatus:@"网络错误"];
            }
        }
        
        [self.myTableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
        if (buttonIndex == 0)
        {
            WPMineLoginVC *vc = [WPMineLoginVC new];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
        }
}

-(void)loadMoreData
{
    
    
     NSString *url = @"user/getExchRecord.do";
    NSDictionary *dict = @{@"page":@(self.indexPage)};
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"%zd*****%@",self.indexPage,responseObject);
        if ([responseObject[@"result"] isEqualToString:@"success"])
        {
            if([responseObject[@"detail"] count])
            {
                for (NSDictionary *recordDict in responseObject[@"detail"])
                {
                    WPGoldRecordsModel *model = [WPGoldRecordsModel yy_modelWithDictionary:recordDict];
                    [self.models addObject:model];
                }
                
                self.indexPage++;
                
                [self.myTableView reloadData];
                
                if ([responseObject[@"detail"] count] < 10)
                {
                    [self.myTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
        }
        else
        {
            [self.myTableView.mj_footer endRefreshing];
            
            //考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                //账号过期
                [self illegalLoginWithSuccessBlock:^{
                    
                    //点击确定后的回调
                    WPMineLoginVC *vc = [WPMineLoginVC new];
                    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                }];
            }
            else
            {
                [self showErrorInfoWithStatus:@"网络错误"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

- (IBAction)back:(id)sender
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 数据源方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WPGoldRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WPGoldRecordCell"];
    
    WPGoldRecordsModel *model = self.models[indexPath.item];
    cell.model = model;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"WPGoldRecordCell" cacheByIndexPath:indexPath configuration:^(WPGoldRecordCell *cell) {
        // 配置 cell 的数据源，和 "cellForRow" 干的事一致，比如：
        cell.model = self.models[indexPath.row];
    }];
}

@end









